const {sendSMScode} =require("ali-sms")

const {
  verifyCaptcha
} = require('../../lib/utils/captcha')
const {
  ERROR
} = require('../../common/error')

const {
  getVerifyCode
} = require('../../common/utils')

/**
 * 发送短信验证码
 * @tutorial https://uniapp.dcloud.net.cn/uniCloud/uni-id-pages.html#send-sms-code
 * @param {Object} params
 * @param {String} params.mobile    手机号
 * @param {String} params.captcha   图形验证码
 * @param {String} params.scene     短信验证码使用场景
 * @returns
 */
module.exports = async function (params = {}) {
  const schema = {
    mobile: 'mobile',
    captcha: 'string',
    scene: 'string'
  }
  this.middleware.validate(params, schema)
  const {
    mobile,
    captcha,
    scene
  } = params
  
  // 检查图形验证码是否正确
  await verifyCaptcha.call(this, {
    scene: 'send-sms-code',
    captcha
  })

  // -- 测试代码
  // 写入验证码
  let code = getVerifyCode()
  await require('../../lib/utils/verify-code')
    .setMobileVerifyCode.call(this, {
      mobile: params.mobile,
      code: code,
      expiresIn: 180,
      scene
    })
  // return {
  //   errCode: 0,
  //   errMsg: '发送成功'
  // }
  // -- 测试代码

	// 阿里云短信发送验证码，并返回发送结果给前端
	
	let res=await sendSMScode({
		phoneNumber:params.mobile,
		code: code
	})
	return {
	  errCode: 0,
	  sendRes:res,
	  errMsg: '发送成功'
	}

}
